import base64
import hmac
import time
from urllib.parse import quote


def token(_et, _method, _res, _version, _key):

    # 对access_key进行decode
    devKey = base64.b64decode(_key)

    # 计算sign
    org = _et + "\n" + _method + "\n" + _res + "\n" + _version

    sign_b = hmac.new(key=devKey, msg=org.encode(), digestmod=_method)
    sign = base64.b64encode(sign_b.digest()).decode()

    # value 部分进行url编码，method/res/version值较为简单无需编码
    sign = quote(sign, safe="")
    res = quote(_res, safe="")

    # token参数拼接
    token = "version=%s&res=%s&et=%s&method=%s&sign=%s" % (
        _version,
        res,
        _et,
        _method,
        sign,
    )

    return token


if __name__ == "__main__":

    pruductID = "2350"
    et = "1722441600"  # 2024-08-01 00:00:00
    method = "sha1"
    version = "2018-10-31"

    deviceList = [
        {
            "site": "双文街金湖公园-测试",
            "clientId": "88.190.000762%2F020000000000018",
            "deviceName": "test",
            "sign": "qRnTQ0WWfnOK3uYk08QFtavqh+=",
        },
    ]

    # 污水井
    for device in deviceList:
        print(
            device["site"],
            token(
                et,
                method,
                "products/"
                + pruductID
                + "/devices/"
                + (device["clientId"]),  # .replace("//", "5%2F")),
                version,
                device["sign"],
            ),
        )
